package com.thkj.modules.user.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.abel533.entity.Example;
import com.thkj.common.util.PropertiesUtils;
import com.thkj.modules.dao.LoginRecordMapper;
import com.thkj.modules.user.entity.LoginRecord;
import com.thkj.modules.user.entity.TblSecurityAdmin;
import com.thkj.modules.user.service.ILoginRecordService;

import dp.util.DateUtil;

@Service("loginRecordService")
public class LoginRecordServiceImpl implements ILoginRecordService {

	@Autowired
	private LoginRecordMapper loginRecordDao;

	public void save(TblSecurityAdmin rmPerson) {
		LoginRecord loginRecord = new LoginRecord();
		loginRecord.setUserId(rmPerson.getId());
		loginRecord.setUsername(
				StringUtils.isNotBlank(rmPerson.getRealName()) ? rmPerson.getRealName() : rmPerson.getNickName());
		loginRecord.setVisitTime(DateUtil.getNowAsTimestamp());
		loginRecord.setHeadUrl(rmPerson.getImageUrl());
		loginRecord.setAccount(rmPerson.getLoginName());
		Example example = new Example(LoginRecord.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("account", rmPerson.getLoginName());
		List<LoginRecord> select = loginRecordDao.selectByExample(example);
		if (select != null && select.size() > 0) {
			LoginRecord loginRecord1 = select.get(0);
			loginRecord.setVisitTime(DateUtil.getNowAsTimestamp());
			loginRecordDao.updateByPrimaryKey(loginRecord1);
		} else {
			loginRecordDao.insert(loginRecord);
		}
	}

	@Override
	public List<LoginRecord> queryByRecen() {

		Example example = new Example(LoginRecord.class);
		example.setOrderByClause("visit_time DESC");

		List<LoginRecord> records = loginRecordDao.selectByExample(example);
		return records.stream().map(loginRecord -> {
			if (StringUtils.isBlank(loginRecord.getHeadUrl())) {
				loginRecord.setHeadUrl(PropertiesUtils.getProperty("sys.constants.manage.head.default.url"));
			}
			return loginRecord;
		}).collect(Collectors.toList());
	}
}
